<?php

namespace app\controller\admin\material;

use app\model\admin\basic\BasicContent;
use app\model\admin\material\MaterialGame;
use app\model\admin\material\MaterialGroup;
use app\model\admin\material\MaterialGroupData;
use app\model\admin\material\MaterialGroupDataMaterial;
use app\model\admin\material\MaterialStyle;
use app\model\admin\material\MaterialTitle;
use app\model\admin\material\MaterialTitleContent;
use laytp\controller\Backend;
use think\Exception;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Data extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info','import'];

    public function initialize()
    {
        $this->model = new MaterialGroupData();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data = $this->model->with(['group', 'content'])->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
                if (isset($item['url']) && !empty($item['url'])) {
                    $item['url'] = imgUrlToAbsolute($item['url']);
                }
                if (isset($item['icon']) && !empty($item['icon'])) {
                    $item['icon'] = imgUrlToAbsolute($item['icon']);
                }
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        if (!$this->request->param("game_id")) {
            return $this->error("缺少游戏id");
        }
        $gameId = $this->request->param("game_id");
        $post = $this->request->post();
        try {
            $post['material_game_id'] = $gameId;
            $data = [
                'label' => $post['label'],
                'material_group_id' => $post['material_group_id'],
                'content_id' => $post['content_id'],
                'material_game_id' => $gameId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            Db::startTrans();
            $id = $this->model->insertGetId($data);
            if ($id) {
                $new = [];
                if (isset($post['special_id']) && !empty($post['special_id'])) {
                    $special_ids = $post['special_id'];
                    if (isset($post['special_number'])) {
                        $special_number = $post['special_number'];
                        foreach ($special_ids as $key => $item) {
                            if (empty($item)) {
                                continue;
                            }
                            if (!isset($special_number[$key])) {
                                continue;
                            }
                            $new[] = [
                                'material_group_data_id' =>$id,
                                'material_unit' => $item,
                                'type' => 2,
                                'material_id' => "",
                                'number' => $special_number[$key],
                            ];
                        }
                    }
                }
                if (isset($post['material_id']) && !empty($post['material_id'])) {
                    $material_ids = $post['material_id'];
                    if (isset($post['material_number'])) {
                        $material_number = $post['material_number'];
                        foreach ($material_ids as $key => $item) {
                            if (empty($item)) {
                                continue;
                            }
                            if (!isset($material_number[$key])) {
                                continue;
                            }
                            $new[] = [
                                'material_group_data_id' =>$id,
                                'material_unit' => "",
                                'type' => 1,
                                'material_id' => $item,
                                'number' => $material_number[$key],
                            ];
                        }
                    }
                }
                if(count($new)>0){
                    (new MaterialGroupDataMaterial())->insertAll($new);
                }else{
                    Db::rollback();
                    return $this->error('请选择材料');
                }
                $this->clearCache();
                Db::commit();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $post = $this->request->post();

        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        try {
            Db::startTrans();
            $updateRes = $info->save();
            if ($updateRes) {
                $new = [];
                (new MaterialGroupDataMaterial())->where("material_group_data_id",$id)->delete();
                if (isset($post['special_id']) && !empty($post['special_id'])) {
                    $special_ids = $post['special_id'];
                    if (isset($post['special_number'])) {
                        $special_number = $post['special_number'];
                        foreach ($special_ids as $key => $item) {
                            if (empty($item)) {
                                continue;
                            }
                            if (!isset($special_number[$key])) {
                                continue;
                            }
                            $new[] = [
                                'material_group_data_id' =>$id,
                                'material_unit' => $item,
                                'type' => 2,
                                'material_id' => "",
                                'number' => $special_number[$key],
                            ];
                        }
                    }
                }
                if (isset($post['material_id']) && !empty($post['material_id'])) {
                    $material_ids = $post['material_id'];
                    if (isset($post['material_number'])) {
                        $material_number = $post['material_number'];
                        foreach ($material_ids as $key => $item) {
                            if (empty($item)) {
                                continue;
                            }
                            if (!isset($material_number[$key])) {
                                continue;
                            }
                            $new[] = [
                                'material_group_data_id' =>$id,
                                'material_unit' => "",
                                'type' => 1,
                                'material_id' => $item,
                                'number' => $material_number[$key],
                            ];
                        }
                    }
                }
                if(count($new)>0){
                    (new MaterialGroupDataMaterial())->insertAll($new);
                }else{
                    Db::rollback();
                    return $this->error('请选择材料');
                }
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::rollback();

                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    public function info()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (is_object($info)) $info = $info->toArray();
        $materials = (new MaterialGroupDataMaterial())->where("material_group_data_id",$id)->select()->toArray();
        $info['special'] = [];
        $info['material'] = [];
        foreach ($materials as $item){
            if($item['type']==1){
                $info['material'][] =$item;
            }else{
                $info['special'][] =$item;
            }
        }
        return $this->success('获取成功', $info);
    }

    //删除
    public function del()
    {
        $ids = array_filter($this->request->post('ids'));
        if (!$ids) {
            return $this->error('参数ids不能为空');
        }
        try{
            Db::startTrans();
            if ($this->model->destroy($ids)) {
                (new MaterialGroupDataMaterial())->whereIn("material_group_data_id",$ids)->delete();
                $this->clearCache();
                Db::commit();
                return $this->success('数据删除成功');
            } else {
                return $this->error('数据删除失败');
            }
        }catch (\Exception $e){
            return $this->exceptionError($e);
        }
    }

    /**
     * 导入条数
     * @return false|string|\think\response\Json
     */
    public function import(){
        $file = $this->request->file("file");
        $game_id  = $this->request->post("game_id");
        $styleList = (new MaterialStyle())->where("material_game_id", $game_id)->where("status", 1)->column("*",'id');
        $childrenData = [];
        $titleIds = array_column($styleList,"title_id");
        $titleContents = (new MaterialTitle())
            ->whereIn("id",$titleIds)->where("status",1)->where("type",2)->column("content_ids","id");
        $contentIds = [];
        foreach ($titleContents as &$item){
            $item = explode(",",$item);
            $contentIds = array_merge($contentIds,$item);
        }
        $contents = (new BasicContent())->whereIn("id",array_unique($contentIds))->where("status",1)->column("name","id");
        foreach ($titleContents as $key=>$item) {
            foreach ($item as $i){
                if(isset($contents[$i])){
                    $childrenData[$key][$contents[$i]] = [
                        "id" => $i,
                        "pid" => "s" . $key,
                        "name" => $contents[$i],
                    ];
                }
            }
        }
        foreach ($styleList as $key=>$item){
            $item['pid'] = 0;
            if (isset($childrenData[$item['title_id']])) {
                $styleList[$key]['children'] = $childrenData[$item['title_id']];
                $styleList[$key]['id'] = "s" . $item['title_id'];
            }else{
                unset($styleList[$key]);
            }
        }
        $basic_game_id = (new MaterialGame())->where("id",$game_id)->value("basic_game_id");
        if(empty($basic_game_id)){
            return $this->error('游戏未绑定基础资料');
        }
//        $materialList = (new BasicContent())->where('basic_game_id',$basic_game_id)->where("status",1)->column("id","name");
        $titles = (new MaterialTitle())->where('material_game_id',$game_id)->where("type",1)->where("status",1)->column("id");
        $contentIds = (new MaterialTitleContent())->whereIn("material_title_id",$titles)->column("id");
        $styleIds = (new MaterialStyle())->where("material_game_id",$game_id)->column("id");
        $groupIds = (new MaterialGroup())->where("material_game_id",$game_id)->where("status",1)->column("id");
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
        $sheetData = $spreadsheet->getActiveSheet(1)->toArray(null, true, true, true);
        unset($sheetData[1]);
        $model = new MaterialGroupData();
        $materialModel = new MaterialGroupDataMaterial();
        Db::startTrans();
        foreach ($sheetData as $item){
            if(empty($item['A'])||empty($item['C'])||empty($item['D'])||$item['E']==''){
                continue;
            }
            if(!in_array($item['A'],$groupIds)){
                continue;
            }
            if(!in_array($item['C'],$styleIds)){
                continue;
            }
            if(!in_array($item['D'],$contentIds)){
                continue;
            }
            $newData = [
                'material_game_id' =>$game_id,
                'material_group_id' =>$item['A'],
                'content_id' =>$item['D'],
                'label' =>$item['E'],
                'status' =>1,
                'create_time' =>date("Y-m-d H:i:s"),
                'update_time' =>date("Y-m-d H:i:s"),
            ];
            $id = "";
            try {
                $id = $model->insertGetId($newData);
            }catch (Exception $exception){
                if($exception->getCode()==10501){
                    continue;
                }
            }
            if(!empty($id)){
                $materialsData = [];
                if(!empty($item['F'])&&!empty($item['G'])){
                    $materialsData[] =[
                        'material_group_data_id' =>$id,
                        'material_unit' =>$item['C']."-".$item['F'],
                        'number' =>$item['G'],
                        'type' =>2,
                        'material_id' =>"",
                    ];
                }
                if(!empty($item['H'])&&!empty($item['I'])){
                    $materialsData[] =[
                        'material_group_data_id' =>$id,
                        'material_unit' =>$item['C']."-".$item['H'],
                        'number' =>$item['I'],
                        'type' =>2,
                        'material_id' =>"",
                    ];
                }
                if(!empty($item['J'])&&!empty($item['K'])){
                    $materialsData[] =[
                        'material_group_data_id' =>$id,
                        'material_unit' =>$item['C']."-".$item['J'],
                        'number' =>$item['K'],
                        'type' =>2,
                        'material_id' =>"",
                    ];
                }
                if(!empty($item['L'])&&!empty($item['M'])){
                    $materialsData[] =[
                        'material_group_data_id' =>$id,
                        'material_unit' =>$item['C']."-".$item['L'],
                        'number' =>$item['M'],
                        'type' =>2,
                        'material_id' =>"",
                    ];
                }
                if(!empty($item['N'])&&!empty($item['O'])){
                    $materialsData[] =[
                        'material_group_data_id' =>$id,
                        'material_unit' =>$item['C']."-".$item['N'],
                        'number' =>$item['O'],
                        'type' =>2,
                        'material_id' =>"",
                    ];
                }
                if(!empty($item['P'])&&!empty($item['Q'])){
                    $materialsData[] =[
                        'material_group_data_id' =>$id,
                        'material_unit' =>$item['C']."-".$item['P'],
                        'number' =>$item['Q'],
                        'type' =>2,
                        'material_id' =>"",
                    ];
                }
                if(!empty($item['R'])&&!empty($item['S'])){
                    $materialsData[] =[
                        'material_group_data_id' =>$id,
                        'material_unit' =>$item['C']."-".$item['R'],
                        'number' =>$item['S'],
                        'type' =>2,
                        'material_id' =>"",
                    ];
                }
                if(!empty($item['T'])&&!empty($item['U'])){
                    $materialsData[] =[
                        'material_group_data_id' =>$id,
                        'material_unit' =>$item['C']."-".$item['T'],
                        'number' =>$item['U'],
                        'type' =>2,
                        'material_id' =>"",
                    ];
                }
                if(!empty($item['V'])&&!empty($item['W'])){
                    if(isset($styleList[$item['C']]['children'][$item['V']])){
                        $materialsData[] =[
                            'material_group_data_id' =>$id,
                            'material_unit' =>"",
                            'number' =>$item['W'],
                            'type' =>1,
                            'material_id' =>$styleList[$item['C']]['children'][$item['V']]['id'],
                        ];
                    }
                }
                if(!empty($item['X'])&&!empty($item['Y'])){
                    if(isset($styleList[$item['C']]['children'][$item['X']])){
                        $materialsData[] =[
                            'material_group_data_id' =>$id,
                            'material_unit' =>"",
                            'number' =>$item['Y'],
                            'type' =>1,
                            'material_id' =>$styleList[$item['C']]['children'][$item['X']]['id'],
                        ];
                    }
                }
                if(!empty($item['Z'])&&!empty($item['AA'])){
                    if(isset($styleList[$item['C']]['children'][$item['Z']])){
                        $materialsData[] =[
                            'material_group_data_id' =>$id,
                            'material_unit' =>"",
                            'number' =>$item['AA'],
                            'type' =>1,
                            'material_id' =>$styleList[$item['C']]['children'][$item['Z']]['id'],
                        ];
                    }
                }
                if(!empty($item['AB'])&&!empty($item['AC'])){
                    if(isset($styleList[$item['C']]['children'][$item['AB']])){
                        $materialsData[] =[
                            'material_group_data_id' =>$id,
                            'material_unit' =>"",
                            'number' =>$item['AC'],
                            'type' =>1,
                            'material_id' =>$styleList[$item['C']]['children'][$item['AB']]['id'],
                        ];
                    }
                }
                if(!empty($item['AD'])&&!empty($item['AE'])){
                    if(isset($styleList[$item['C']]['children'][$item['AD']])){
                        $materialsData[] =[
                            'material_group_data_id' =>$id,
                            'material_unit' =>"",
                            'number' =>$item['AE'],
                            'type' =>1,
                            'material_id' =>$styleList[$item['C']]['children'][$item['AD']]['id'],
                        ];
                    }
                }
                if(!empty($item['AF'])&&!empty($item['AG'])){
                    if(isset($styleList[$item['C']]['children'][$item['AF']])){
                        $materialsData[] =[
                            'material_group_data_id' =>$id,
                            'material_unit' =>"",
                            'number' =>$item['AG'],
                            'type' =>1,
                            'material_id' =>$styleList[$item['C']]['children'][$item['AF']]['id'],
                        ];
                    }
                }
                if(!empty($item['AH'])&&!empty($item['AI'])){
                    if(isset($styleList[$item['C']]['children'][$item['AH']])){
                        $materialsData[] =[
                            'material_group_data_id' =>$id,
                            'material_unit' =>"",
                            'number' =>$item['AI'],
                            'type' =>1,
                            'material_id' =>$styleList[$item['C']]['children'][$item['AH']]['id'],
                        ];
                    }
                }
                if(!empty($item['AJ'])&&!empty($item['AK'])){
                    if(isset($styleList[$item['C']]['children'][$item['AJ']])){
                        $materialsData[] =[
                            'material_group_data_id' =>$id,
                            'material_unit' =>"",
                            'number' =>$item['AK'],
                            'type' =>1,
                            'material_id' =>$styleList[$item['C']]['children'][$item['AJ']]['id'],
                        ];
                    }
                }
                if(count($materialsData)>0){
                    $materialModel->insertAll($materialsData);
                }
            }

        }
        Db::commit();
        return $this->success("上传成功");
    }
}